package com.tiny.tinyweb.core.utils;

import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class SecurityUtils {
    /** 加密算法 */
    private static final String SECRET_AES_KEY = "AES";

    /** 加密方式 */
    private static final String ENC_AES_KEY = "AES/CBC/PKCS5Padding";

    /** IV */
    private static final String IV_VALUE = "FCbbo9nzJofN31rN";

    /**
     * 根据指定Key对字符串进行MD5加密。
     * @param target 加密对象字符串
     * @param key 加密Key
     * @return 加密后的字符串
     * @throws Exception 加密时可能出现的异常
     */
    public static String encryptAES(String target, String key) throws Exception {
        // 生成128bit的加密Key
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.reset();
        messageDigest.update(key.getBytes());
        SecretKey secretKey = new SecretKeySpec(messageDigest.digest(), SECRET_AES_KEY);

        // 加密
        Cipher cipher = Cipher.getInstance(ENC_AES_KEY);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(IV_VALUE.getBytes()));
        byte encrypted[] = cipher.doFinal(target.getBytes());

        // 加密结果进行Base64编码
        String encodeBase64 = new String(Base64.encodeBase64(encrypted));

        // 替换特殊字符
        encodeBase64 = encodeBase64.toString().replace("/", "_");
        encodeBase64 = encodeBase64.toString().replace("+", "-");

        // 返回加密结果
        return encodeBase64;
    }

    /**
     * 根据指定Key对MD5加密后的字符串进行解密。
     * @param target 解密对象字符串
     * @param key 解密Key
     * @return 解密后的字符串
     * @throws Exception 解密时可能出现的异常
     */
    public static String decryptAES(String target, String key) throws Exception {
        // 生成128bit的解密Key
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.reset();
        messageDigest.update(key.getBytes());
        SecretKey secretKey = new SecretKeySpec(messageDigest.digest(), SECRET_AES_KEY);

        // 替换特殊字符
        String token;
        token = target.toString().replace("_", "/");
        token = token.toString().replace("-", "+");

        // Base64解码
        byte[] targetBytes = Base64.decodeBase64(token.getBytes());

        // 解密
        Cipher cipher = Cipher.getInstance(ENC_AES_KEY);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(IV_VALUE.getBytes()));
        byte decrypted[] = cipher.doFinal(targetBytes);

        // 返回解密结果
        return new String(decrypted);
    }
}
